package domein.models;

import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;

import domein.Peer;
import domein.PeerController;
import domein.models.Observer;

public class PeersListModel extends AbstractTableModel implements Observer 
{
	private static final long serialVersionUID = 1L;
	private PeerController peerController;
	private String[] columnNames = {"Peername", "IP-Adres"};
	private List<Peer> peerList = new ArrayList<Peer>();
	
	public PeersListModel(PeerController peerController)
	{
		this.peerController = peerController;
		this.peerController.addObserver(this);
		this.peerList = PeerController.getInstance().getAllPeers();
	}
	
	@Override
	public void update() 
	{
		peerList = PeerController.getInstance().getAllPeers();
		fireTableDataChanged();
		
		if (PeerController.getInstance().getBestandenListModel().getSelectedPeer() == null && peerList.size() > 0)
		{
			PeerController.getInstance().getBestandenListModel().setSelectedPeer(peerList.get(0));
		}
	}

	@Override
	public int getColumnCount() 
	{
		return columnNames.length;
	}

	@Override
	public int getRowCount() 
	{
		return peerList.size();
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) 
	{
		return peerList.get(rowIndex).toArray()[columnIndex];	
	}
	
	public String getColumnName(int columnIndex){
		return this.columnNames[columnIndex];
	}
	
	public Peer getPeerForIndex(int index)
	{
		Peer peer = peerList.get(index);
		return peer;
	}
}
